//
//  TDriveCarDatePicker.m
//  TBRentClient
//
//  Created by tonbright on 2018/6/8.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "TDriveCarDatePicker.h"
#import "YXDateHelpObject.h"
#import "TDCarSourceModel.h"
#import "NetWorkRequest.h"
#import "IANActivityIndicatorButton.h"
#import "UIButton+IANActivityView.h"

@interface TDriveCarDatePicker ()<UIPickerViewDataSource,UIPickerViewDelegate>


@property (nonatomic,strong)NSMutableArray *dateArray;
@property (nonatomic,strong)NSMutableArray *actualDateArray;//记录包含年月日的时间--避免后面根据月日来计算的时候出现跨年情况的 年份出现bug------------

@property (nonatomic,strong)NSMutableArray *timeDurationArray;

@property (nonatomic,copy)NSString *currentDateStr;


@property (nonatomic,strong)IANActivityIndicatorButton *btn_showResult;
@property (nonatomic,copy)NSString *totalCarNum;

@end

@implementation TDriveCarDatePicker

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
    self.dateArray = [[YXDateHelpObject manager] latelyTime:150];
    self.actualDateArray = [[YXDateHelpObject manager] latelyTimeYearMonthDay:150];
    [_dateArray removeObjectAtIndex:0];
    [_actualDateArray removeObjectAtIndex:0];
    self.timeDurationArray = @[@"",@"3",@"5",@"7"].mutableCopy;

    _view_big.layer.borderColor = [UIColor colorWithHex:0xa9a9a9].CGColor;
    _view_big.layer.borderWidth = 1;
    _view_bottom.layer.borderColor = [UIColor colorWithHex:0xa9a9a9].CGColor;
    _view_bottom.layer.borderWidth = 1;
    
    [self.pickerView selectRow:0 inComponent:0 animated:NO];
    [self.pickerView selectRow:0 inComponent:1 animated:NO];
    [self pickerView:self.pickerView didSelectRow:0 inComponent:0];
    [self pickerView:self.pickerView didSelectRow:0 inComponent:1];
    [self setBtnShow];
}

- (void)setBtnShow {
    __weak typeof(self) weakSelf = self;
    _btn_showResult = [[IANActivityIndicatorButton alloc] init];
    _btn_showResult.frame = CGRectMake(0, 5, Width - 40, 40);
    _btn_showResult.backgroundColor = [UIColor colorWithHex:0xbf0021];
    _btn_showResult.layer.cornerRadius = 5;
    [_view_bottom addSubview:_btn_showResult];
    [_btn_showResult setTitle:@"显示结果" forState:UIControlStateNormal];
    _btn_showResult.TouchBlock = ^(IANActivityIndicatorButton *myButton){
        if (weakSelf.pickerViewSureBtnBlock) {
            //吧年月日保存起来吗?---------
            //            NSString *yearStr = self.actualDateArray[dateIndex];
            //            NSString *dateStr = self.dateArray[dateIndex];
            //            NSString *timeDurationStr = self.timeDurationArray[timeDurationIndex];
            
            weakSelf.pickerViewSureBtnBlock(weakSelf.dateSelModel);
            [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelDateModel = weakSelf.dateSelModel;
        }
    };
}


- (void)setDefaultBtnShow {
    [_btn_showResult endButtonActivityIndicatorView];
    [_btn_showResult setTitle:@"显示结果" forState:UIControlStateNormal];
}

- (void)setSelBtnShow {
    [_btn_showResult startButtonActivityIndicatorView];
    [_btn_showResult setTitle:@"加载中" forState:UIControlStateNormal];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.dateArray.count;
    }
    return self.timeDurationArray.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    if (component == 0) {
        return Width / 2;
    }else {
        return Width / 2;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return self.dateArray[row];
    }else{
        if (row == 0) {
            return @"";
        }
        return [NSString stringWithFormat:@"试驾%@天",self.timeDurationArray[row]];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    [self setLbe_titleText];
    if (component == 0) {
        NSInteger dateIndex = row;
        NSString *yearStr = self.actualDateArray[dateIndex];
        NSString *dateStr = self.dateArray[dateIndex];
        self.dateSelModel.yearStr = yearStr;
        self.dateSelModel.dateStr = dateStr;
        self.dateSelModel.yearIndex = dateIndex;
    }else {
        NSInteger timeDurationIndex = row;
        NSString *timeDurationStr = self.timeDurationArray[timeDurationIndex];
        self.dateSelModel.hourIndex = timeDurationIndex;
        self.dateSelModel.timeDurationStr = timeDurationStr;
    }
    [self loadAllCarSourceListNetData];
}


- (IBAction)cancleBtnClick:(UIButton *)sender {
    if (sender.tag == 10) {
        if (self.pickerViewCancleBtnBlock) {
            self.pickerViewCancleBtnBlock();
        }
    }else if (sender.tag == 20) {
//        NSInteger dateIndex = [self.pickerView selectedRowInComponent:0];
//        NSInteger timeDurationIndex = [self.pickerView selectedRowInComponent:1];
//        NSLog(@"%ld-----%ld",dateIndex,timeDurationIndex);
        if (self.pickerViewSureBtnBlock) {
            //吧年月日保存起来吗?---------
//            NSString *yearStr = self.actualDateArray[dateIndex];
//            NSString *dateStr = self.dateArray[dateIndex];
//            NSString *timeDurationStr = self.timeDurationArray[timeDurationIndex];
            
            self.pickerViewSureBtnBlock(self.dateSelModel);
            [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelDateModel = _dateSelModel;
        }
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (self.pickerViewCancleBtnBlock) {
        self.pickerViewCancleBtnBlock();
    }
}


- (TDDriveCarDatePickerSelModel *)dateSelModel {
    if (!_dateSelModel) {
        _dateSelModel  =[[TDDriveCarDatePickerSelModel alloc] init];
    }
    return _dateSelModel;
}


// MARK: - 设置顶部文本字体变化
- (void)setLbe_titleText {
    //吧年月日保存起来吗?---------
    NSInteger dateIndex = [self.pickerView selectedRowInComponent:0];
    NSInteger timeDurationIndex = [self.pickerView selectedRowInComponent:1];
    if (timeDurationIndex==0) {
        _lbe_title.text = @"选择试驾时间";
        return;
    }
    NSString *yearStr = self.actualDateArray[dateIndex];
    NSString *dateStr = self.dateArray[dateIndex];
    NSString *timeDurationStr = self.timeDurationArray[timeDurationIndex];
    NSDate *yearTmpDate = [[YXDateHelpObject manager] getDataFromStrFormat:@"yyyy/M/dd" String:yearStr];
    NSDate *endDate = [[YXDateHelpObject manager] getEarlyOrLaterDate:yearTmpDate LeadTime:timeDurationStr.integerValue-1 Type:2];
    NSString *endDateStr = [[YXDateHelpObject manager] getCurentTime:@"M月dd日" dateN:endDate];
    self.dateSelModel.yearStr = yearStr;
    self.dateSelModel.yearEndStr = [[YXDateHelpObject manager] getCurentTime:@"yyyy/MM/dd" dateN:endDate];
    self.dateSelModel.timeDurationStr = timeDurationStr;
    self.dateSelModel.dateStr = dateStr;
    NSString *startDateStr = [dateStr componentsSeparatedByString:@" "].firstObject;
    NSString *showDateStr = [HelpObject isBlankString:dateStr] ? @"选择试驾时间" : [NSString stringWithFormat:@"%@ - %@",startDateStr,endDateStr];
    self.dateSelModel.showDateStr = [showDateStr isEqualToString:@"选择试驾时间"] ? nil : showDateStr;
    //吧年月日保存起来吗?---------
    _lbe_title.text = showDateStr;
}

- (IBAction)cleanDateBtnClick:(UIButton *)sender {
    [self pickerView:self.pickerView didSelectRow:0 inComponent:0];
    [self pickerView:self.pickerView didSelectRow:0 inComponent:1];
    self.dateSelModel = [[TDDriveCarDatePickerSelModel alloc] init];
    self.lbe_title.text = @"选择试驾时间";
}



// MARK: - 获取网络数据-----
- (void)loadAllCarSourceListNetData {
    NSInteger timeDurationIndex = [self.pickerView selectedRowInComponent:1];
    if (timeDurationIndex == 0) {
        [self setDefaultBtnShow];
        self.dateSelModel = [[TDDriveCarDatePickerSelModel alloc] init];
        return;
    }
    //    [NetWorkRequest cancel];
    [self setSelBtnShow];
    // MARK: - 获取车源列表--------------
    if (!_locationModel) {
        self.noticeText = @"定位失败,请稍后重试";
        return;
    }
    if ([HelpObject isBlankString:[AppSetting shareAppSetting].topcompanyid]) {
        self.noticeText = @"顶级公司id为空";
        return;
    }
    self.selStoreModel = [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelStoreModel;
    NSString *topcompanyid = [AppSetting shareAppSetting].topcompanyid;
    NSMutableDictionary *parDic = @{@"topcompanyid":topcompanyid,
                                    @"longitude":_locationModel.longitude,
                                    @"latitude":_locationModel.latitude,
                                    @"prevrows":@"0",
                                    @"showrows":@"1",
                                    }.mutableCopy;
    [self setParaDic:parDic];
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest postNetRequestData:CarListTD parmeters:parDic response:^(NSDictionary *response) {
        [weakSelf.btn_showResult endButtonActivityIndicatorView];
        if (response) {
            weakSelf.totalCarNum = [HelpObject changeNull:response[@"data"][@"total"]];
            NSString *tmpStr = [NSString stringWithFormat:@"显示%@车源",weakSelf.totalCarNum];
            [weakSelf.btn_showResult setTitle:tmpStr forState:UIControlStateNormal];
        }else {
        }
    } netError:^(NSError *error) {
        [weakSelf.btn_showResult endButtonActivityIndicatorView];
    }];
}


- (void)setParaDic:(NSMutableDictionary *)paraDic {
    
    NSString *tmpWorkdayf = [_dateSelModel.yearStr stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    NSString *tmpWorkdayT = [_dateSelModel.yearEndStr stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    
    [paraDic setValue:[HelpObject changeNull:tmpWorkdayf] forKey:@"workdayf"];
    [paraDic setValue:[HelpObject changeNull:tmpWorkdayT] forKey:@"workdayt"];
    [paraDic setValue:[HelpObject changeNull:_selStoreModel.searchStoreModel.storeid] forKey:@"storeid"];
    
    [paraDic setValue:[HelpObject changeNull:_selModel.brandid] forKey:@"brandid"];
    
    [paraDic setValue:[HelpObject changeNull:_tf_search_str] forKey:@"cartype"];
    [paraDic setValue:[HelpObject changeNull:_selModel.seriesid] forKey:@"seriesid"];
    [paraDic setValue:[TDCarSourceAllMessageModel shareAllMessageModel].orders forKey:@"orders"];
}

@end
